using System;
using System.Collections.Generic;
using UMC.Web;

using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow
{


    [Apiumc("WorkFlow", "Button", Auth = WebAuthType.Admin, Desc = "配置流程审批按钮")]
    public class DesignButtonActivity : WebActivity
    {
        TaskCommand Convert2(List<TaskCommand> list, TaskStatus taskStatus, CommandType command)
        {
            var submt = list.Find(g => g.TaskStatus == taskStatus && g.CommandType == command);
            if (submt == null)
            {
                submt = new TaskCommand { CommandType = command, TaskStatus = taskStatus };
                switch (command)
                {
                    case CommandType.Submit:
                        submt.Text = "提交";
                        break;
                    case CommandType.Save:
                        submt.Text = "保存";
                        break;
                    case CommandType.Lock:
                        submt.Text = "锁定";
                        break;
                    case CommandType.Reject:
                        submt.Text = "驳回";
                        break;
                    case CommandType.Approval:
                        submt.Text = "通过";
                        break;
                    case CommandType.Apostille:
                        submt.Text = "加签";
                        break;
                    case CommandType.Terminate:
                        submt.Text = "终止";
                        break;
                }
            }
            return submt;

        }
        WebMeta Convert(List<TaskCommand> list, TaskStatus taskStatus, CommandType command)
        {
            var submt = Convert2(list, taskStatus, command);


            var data = new WebMeta().Put("Text", submt.Text).Put("Command", submt.CommandType.ToString()).Put("Visible", submt.Hidden == true ? "隐藏" : "显示");
            switch (submt.TaskStatus)
            {
                case TaskStatus.Prepare:
                    data.Put("Status", "准备");
                    break;
                case TaskStatus.Completed:
                    data.Put("Status", "完成");
                    break;
                case TaskStatus.InReview:
                    data.Put("Status", "审阅");
                    break;
                case TaskStatus.Termination:
                    data.Put("Status", "终止");
                    break;
                case TaskStatus.Locked:
                    data.Put("Status", "锁定");
                    break;
            }

            var Str = "保存";
            switch (submt.CommandType)
            {
                case CommandType.Apostille:
                    Str = "加签";
                    break;
                case CommandType.Approval:
                    Str = "通过";
                    break;
                case CommandType.Lock:
                    Str = "锁定";
                    break;
                case CommandType.Reject:
                    Str = "驳回";
                    break;
                case CommandType.Submit:
                    Str = "申请";
                    break;
                case CommandType.Terminate:
                    Str = "终止";
                    break;
            }

            if (submt.Hidden == true)
            {
                data.Put("Text", "[隐藏]");
            }
            data["Command"] = Str;
            data.Put("Id", String.Format("{0}.{1}", taskStatus, command));
            return data;


        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var Task = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Task", g =>
             {
                 this.Prompt("请传入表单");
                 return this.DialogValue("none");
             })) ?? 0;
            var SId = this.AsyncDialog("Id", "default");

            var design = DataFactory.Instance().TaskForm (Task);
            //  UMC.WorkFlow.TaskRuntime.Database.ObjectEntity<TaskForm>()
            //     .Where.And(new TaskForm { TaskId = Task }).Entities.Single();
            if (design == null)
            {
                this.Prompt("无此流程设计");
            }


            var taskInstance = TaskManager.Form(design.TaskId.Value);

            var ts = new List<TaskCommand>(DataFactory.Instance().TaskCommand(design.TaskId.Value, SId));
            // var entity = UMC.WorkFlow.TaskRuntime.Database.ObjectEntity<TaskCommand>();
            // entity.Where.And().Equal(new TaskCommand { ShapeId = SId, TaskId = design.TaskId })
            // .Entities.Query(dr => ts.Add(dr));
            //var Args = ;
            var Status = this.AsyncDialog("Status", key =>
            {
                //var limit = this.AsyncDialog("limit", "none");

                //if (limit == "none")
                //{
                //    this.Context.Send(new UISectionBuilder(request.Model, request.Command, new UMC.Web.WebMeta().Put("Id", SId).Put("Task", Task))

                //        .RefreshEvent("WorkFlow.Command")
                //            .Builder(), true);
                //}
                //request.Arguments.Remove("limit");
                var ui = UISection.Create(new UITitle("节点按钮"));

                if (SId == "default")
                {
                    ui.AddCell('\uf0e8', "流程节点", "默认");
                    //ui.AddCell()
                }
                else
                {
                    var shape = taskInstance.Shapes.Find(s => s.Id == SId);
                    if (shape != null)
                    {
                        ui.AddCell('\uf0e8', "流程节点", String.Format("{1}({0})", shape.Id, shape.Text));
                        //ui.AddCell('\uf0e8', "所在流程结点", shape.Text);
                    }
                    else
                    {
                        ui.AddCell('\uf0e8', "流程节点", "未知");
                    }

                }
                //ui.AddCell("状态指令", "标题");

                var data = new List<WebMeta>();
                if (taskInstance.Lines.Exists(l => l.ToId == SId))
                {
                    data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Terminate));
                    data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Reject));
                    data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Approval));
                    data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Apostille));
                    //data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Lock));
                    //data.Add(this.Convert(ts, TaskStatus.Locked, CommandType.Approval));
                    //data.Add(this.Convert(ts, TaskStatus.Locked, CommandType.Apostille));
                    data.Add(this.Convert(ts, TaskStatus.Termination, CommandType.Approval));



                }
                else
                {
                    data.Add(this.Convert(ts, TaskStatus.Prepare, CommandType.Submit));
                    data.Add(this.Convert(ts, TaskStatus.Prepare, CommandType.Save));
                    data.Add(this.Convert(ts, TaskStatus.Termination, CommandType.Submit));
                    data.Add(this.Convert(ts, TaskStatus.Termination, CommandType.Save));
                    data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Terminate));
                    if (SId == "default")
                    {
                        data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Approval));
                        data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Apostille));
                        data.Add(this.Convert(ts, TaskStatus.InReview, CommandType.Reject));

                    }
                }
                var ui3 = ui.NewSection();
                var Status = data[0]["Status"];
                ui3.Header.Put("text", $"在“{Status}”的按钮");
                foreach (var meta in data)
                {
                    var s = meta["Status"];
                    if (String.Equals(s, Status) == false)
                    {
                        Status = s;
                        ui3 = ui.NewSection();
                        ui3.Header.Put("text", $"在“{Status}”的按钮");
                    }
                    ui3.AddCell(meta["Command"], meta["Text"]
                        , new UIClick(request.Model, request.Command, new WebMeta(request.Arguments.GetDictionary()).Put(key, meta["Id"])));
                }
                ui.SendTo(this.Context, "WorkFlow.Command");
                //response.Redirect(ui);
                ;
                //var gl = UIDialog.Create(new UIGridDialog.Header("Id", 0).PutField("Status", "流程状态").PutField("Command", "指令").PutField("Text", "标题"), data.ToArray());
                //gl.Title = "节点审批指令";
                //gl.RefreshEvent = "WorkFlow.Command";
                //return gl;

            });
            var Statuss = Status.Split('.');
            var sub = this.Convert2(ts, UMC.Data.Utility.Parse(Statuss[0], TaskStatus.None), UMC.Data.Utility.Parse(Statuss[1], CommandType.Save));
            var Commands = this.AsyncDialog("Command", key =>
            {

                var form = new UIFormDialog() { Title = "审批按钮" };
                form.AddTextValue().Put("流程状态", sub.TaskStatus.ToString()).Put("审批指令", sub.CommandType.ToString());


                form.AddText("标题", "Text", sub.Text);

                //form.AddText("标签", "Tag", sub.Tag).NotRequired();

                form.AddCheckBox("", "Hidden", new ListItemCollection().Put("隐藏", "true", sub.Hidden == true), "N");
                form.Submit("确认", "WorkFlow.Command");
                return form;

            });
            sub.Hidden = Commands["Hidden"].Contains("true");
            sub.Text = Commands["Text"];
            //sub.Tag = Commands["Tag"];
            sub.ShapeId = SId;
            sub.TaskId = design.TaskId;
            DataFactory.Instance().Put(sub);
            // entity.Where.Reset().And().Equal(new TaskCommand
            // {
            //     TaskId = sub.TaskId,
            //     ShapeId = sub.ShapeId,
            //     TaskStatus = sub.TaskStatus,
            //     CommandType = sub.CommandType
            // });

            // entity.IFF(e => e.Update(sub) == 0, e => e.Insert(sub));

            this.Context.Send("WorkFlow.Command", true);// new WebMeta().Put("Task", UMC.Data.JSON.Expression(UMC.Data.JSON.Serialize(this.taskInstance, true))), true);


        }
    }
}